/*
 * commons is a based project implemented
 * Copyright (C) 2024 Jasmine
 */
package com.commons.core.utils;

import java.util.Objects;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * @author Jasmine
 * @version 1.0
 * @date 2021-10-19 11:55:55
 * @see JsonUtils
 * @since JDK1.8
 */
public class JsonUtils {

    public static final Object object = new Object();

    public static ObjectMapper objectMapper;

    public static ObjectMapper getInstance() {
        if (Objects.isNull(objectMapper)) {
            synchronized (object) {
                if (Objects.isNull(objectMapper)) {
                    try {
                        objectMapper = ApplicationContextHolder.getBean(ObjectMapper.class);
                    } catch (Exception e) {
                        objectMapper = new ObjectMapper();
                    }
                }
            }
        }
        return objectMapper;
    }

    public static String writeValueAsString(Object value) {
        String content = "";
        try {
            content = objectMapper.writeValueAsString(value);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
        return content;
    }

    public static <T> T readValue(String content, Class<T> valueType) {
        T result;
        try {
            result = JsonUtils.getInstance().readValue(content, valueType);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
        return result;
    }
}
